package com.qf.sclg.config;

import com.alibaba.fastjson.JSONObject;
import com.qf.sclg.entity.SysUser;
import com.qf.sclg.result.ResponseCode;
import com.qf.sclg.result.ResponseData;
import com.qf.sclg.service.SysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created with IntelliJ IDEA.
 * User: zdk
 * Date: 2021/10/20 16:09
 * Description:
 * Version: V1.0
 */
@Component
public class AuthorizedInterceptor implements HandlerInterceptor {
    Logger logger = LoggerFactory.getLogger(AuthorizedInterceptor.class);
    //释放的路径  白名单
    public static  final String[] noAuthorizes = {
            "/sysUser/login",
            "/sysUser/api/login/"
    };

    @Autowired
    private SysUserService sysUserService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        拦截请求  http://localhost:8080/  sysUser/login
        String requestURI = request.getRequestURI();
        logger.info(requestURI);
        for (String noAuthorize : noAuthorizes){
            if(requestURI.equals(noAuthorize)){
                return true;
            }
        }
        String token = null;
//        获取cookie  key
        Cookie[] cookies = request.getCookies();
        System.out.println(cookies);
        if(cookies != null && cookies.length != 0){
            for (Cookie cookie : cookies){
                if(cookie.getName().equals("token")){
                    token = cookie.getValue();
                    logger.info("本次token为:"+token);
                }
//                if(cookie.getName().equals("token")){
//                    String token = cookie.getValue();
////                    链接redis，去找token是否过期（去数据库中找对应的token是否存在）
//                    SysUser sysUser = sysUserService.queryBySysToken(token);
//                    if(sysUser == null){
////                        当前token过期，拒绝访问
//                        ResponseData responseData = new ResponseData(ResponseCode.USERINFO_EXCEPTION.getCode(), ResponseCode.USERINFO_EXCEPTION.getMessage());
//                        String s = JSONObject.toJSONString(responseData);
//                        response.setContentType("text/html;charset=UTF-8");
//                        response.getWriter().write(s);
//                        response.getWriter().flush();
//                        response.getWriter().close();
//                        return false;
//                    }else {
//                        return true;
//                    }
//                }
            }
        }
//        链接redis，去找token是否过期（去数据库中找对应的token是否存在）
                    SysUser sysUser = sysUserService.queryBySysToken(token);
                    if(sysUser == null){
//                        当前token过期，拒绝访问
                        ResponseData responseData = new ResponseData(ResponseCode.USERINFO_EXCEPTION.getCode(), ResponseCode.USERINFO_EXCEPTION.getMessage());
                        String s = JSONObject.toJSONString(responseData);
                        response.setContentType("text/html;charset=UTF-8");
                        response.getWriter().write(s);
                        response.getWriter().flush();
                        response.getWriter().close();
                        return false;
                    }

        return true;
    }

}
